﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.Framework.Net;
using ZyGames.Framework.RPC.Sockets;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Common.Serialization;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 通过房间邀请码申请进入房间(要根据房间状态IsChangePlayState判断是进入到保险人页面还是玩法页面,如果是玩法页面的话还要判断当前桌子的状态是正在进行游戏还是等待中)
	/// </summary>
	public class Action10039 : BaseAction
	{
		private int _userId;
		private int _tableId;
		private string _tableInviteNum;
		private TableData _currentTable;
		private bool _result = true;
		private GameUser _currentGameUser;
		private string _log = "";
		private bool FirstEnter = true;//是否是第二次进入
		
		public Action10039(HttpGet actionGetter)
			: base((short)ActionType.DZApplyEnterInsuranceRoomByInviteNum, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetString("TableInviteNum", ref _tableInviteNum) &&
				httpGet.GetInt("UserID", ref _userId))
			{
				return true;
			}
			return false;
		}

		private bool SetErrorInfo(string errorInfo)
		{
			this._result = false;
			this._log = errorInfo;
			return true;
		}

		public override bool TakeAction()
		{
			try
			{
				this._currentGameUser = GameTable.Current.GetUser(_userId);
				if (_currentGameUser == null)
				{
					Tool.WriteWarmingLine("10039当前玩家不存在");
					return this.SetErrorInfo("信息有误");
				}
				if (_tableInviteNum.Length != 6)
				{
					Tool.WriteWarmingLine("输入的房间邀请码不符合6位");
					return this.SetErrorInfo("输入的房间邀请码不符合6位");
				}
				if (!Tool.ValidateNum(_tableInviteNum))
				{
					Tool.WriteWarmingLine("输入的房间邀请码不是纯数字的字符串");
					return this.SetErrorInfo("请输入正确的房间邀请码");
				}
				
				var roomData = GameRoom.Current.GetRoomData(1001);
				foreach(var pair in roomData.Tables)
				{
					var table = pair.Value;
					if(table.InviteNum == int.Parse(_tableInviteNum))
					{
						_currentTable = table;
						_tableId = _currentTable.TableId;
						break;
					}
				}
				if (_currentTable == null)
				{
					Tool.WriteWarmingLine(string.Format("消息10039获得房间id:{0}不存在", _tableId));
					return this.SetErrorInfo("请输入正确的房间邀请码");
				}
				//判断是否勾选了不允许旁观功能,如果当前房间是不允许旁观并且是已经在游戏中了则不能加入
				if (_currentTable.CanNotOnLooking && _currentTable.State != TableState.None)
				{
					Tool.WriteWarmingLine("不允许旁观");
					return this.SetErrorInfo("当前房间不允许旁观");
				}
				//var userList = ClientNotifier.GetUserList(_currentTable);
				////判断是否满员
				//if (userList.Count >= 9)
				//{
				//	Tools.Tool.WriteWarmingLine("消息10039邀请码进入的房间已经满员");
				//	return false;
				//}
				var roomInfo = GameRoom.Current.GetRoom(ConfigEnvSet.GetInt("GameSetting.DefaultRoomID", 1001));
				if (roomInfo == null)
					return true;
				FirstEnter = GameRoom.Current.JoinTable(_currentGameUser, roomInfo, _currentTable);
				//强制重置位置跟Ready状态，不知道哪儿改变了
				//_currentGameUser.Property.ResetState(_tableId);
				_result = true;
				return true;
			}
			catch (Exception ex)
			{
				Tool.WriteErrorLine("10039消息异常:" + ex.ToString());
				return false;
			}
		}

		public override void TakeActionAffter(bool state)
		{
			//进入保险人页面
			if (_currentTable != null && _result)
			{
				var userList = ClientNotifier.GetUserList(_currentTable);
				var newlist = new List<IUser>();
				newlist.Add(new SessionUser(_currentGameUser));
				var newParams = new Parameters();
				var tableInfo = Convert.ToBase64String(ProtoBufUtils.Serialize(_currentTable));
				newParams["TableData"] = tableInfo;
				newParams["TableMasterName"] = _currentTable.TableMaster.NickName;
				var headIcons = string.Empty;
				if (!string.IsNullOrEmpty(_currentTable.TableMaster.HeadIconBytes))
					headIcons = _currentTable.TableMaster.HeadIconBytes;
				//newParams["TableMasterHead"] = headIcons;
				newParams["TableMasterUserID"] = _currentTable.TableMaster.UserId;
				//向申请进入房间的人发送其他玩家和房间信息
				ActionFactory.SendAction(newlist, (int)ActionType.DZNotifyOtherInfoForMe, newParams, (asyncResult) =>
				{
					Console.WriteLine("Action 10041 向申请进入房间的人发送其他玩家和房间信息 send result:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail");
				});

				var list = new List<IUser>();
				foreach (var user in userList)
				{
					//排除掉当前进入房间的人
					if (user.GetUserId() != _currentGameUser.GetUserId())
						list.Add(new SessionUser(user));
				}
				if (list.Count <= 0)
				{
					Tool.WriteErrorLine("消息 10039 不存在其他玩家");
					return;
				}
				var parameters = new Parameters();
				parameters["TableID"] = _tableId;
				parameters["UserID"] = _userId;
				parameters["NickName"] = _currentGameUser.NickName;
				//parameters["HeadIcon"] = _currentGameUser.HeadIcon;
				//headIcons = string.Empty;
				//if (!string.IsNullOrEmpty(_currentGameUser.HeadIconBytes))
				//	headIcons = _currentGameUser.HeadIconBytes;
				//parameters["HeadIconBytes"] = headIcons;
				ActionFactory.SendAction(list, (int)ActionType.DZBroadcastApplyEnterInsuranceRoomByInviteNum, parameters, (asyncResult) =>
				{
					Console.WriteLine("Action 10040 广播某玩家通过邀请码进入保险页面 send result:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail");
				});
			}
			base.TakeActionAffter(state);
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this._result);
			this.PushIntoStack(this._log);
		}
	}
}
